﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace November {
    class DateCreatedComparer : IComparer<String> {
        private static readonly IComparer<String> DEFAULT_COMPARER = new AlphaNumericComparer();
        private static Dictionary<String, DateTime> FileCreationTimeCache = new Dictionary<String, DateTime>();

        private static DateTime GetDateTime(String fileName) {
            if (FileCreationTimeCache.ContainsKey(fileName)) {
                return FileCreationTimeCache[fileName];
            }
            DateTime fileCreationTime = File.GetCreationTime(fileName);
            FileCreationTimeCache[fileName] = fileCreationTime;
            return fileCreationTime;
        }

        public Int32 Compare(String x, String y) {
            if (!File.Exists(x) || !File.Exists(y)) return DEFAULT_COMPARER.Compare(x, y);

            DateTime xFileCreationTime = GetDateTime(x);
            DateTime yFileCreationTime = GetDateTime(y);

            if (xFileCreationTime.Year < yFileCreationTime.Year) { return -1; }
            if (xFileCreationTime.Year > yFileCreationTime.Year) { return +1; }
            if (xFileCreationTime.DayOfYear < yFileCreationTime.DayOfYear) { return -1; }
            if (xFileCreationTime.DayOfYear > yFileCreationTime.DayOfYear) { return +1; }

            return DEFAULT_COMPARER.Compare(x, y);
        }
    }
}
